package com.starry.core.logic

import android.util.Log
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

/**
 * @ClassName SharedOKhttpClient
 * @Description 共享的okhttpclient
 * @Author jiangyuntao
 * @Data 2023/7/28 21:20
 * @Version 1.0
 */

object SharedOkHttpClient {
    @Volatile // Ensure visibility of changes across threads
    private var client: OkHttpClient? = null

    fun getClient(): OkHttpClient? {
        if (client == null) {
            synchronized(this) {
                if (client == null) {
                    // 创建一个自定义的 CookieJar
                    val cookieJar: CookieJar = object : CookieJar {
                        private val cookieStore: HashMap<String, List<Cookie>> = HashMap()

                        @Synchronized
                        override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
                            // 保存来自服务器的 Cookie
                            cookieStore[url.host] = cookies
                            Log.d("CookieJar",cookies.toString())
                        }

                        @Synchronized
                        override fun loadForRequest(url: HttpUrl): List<Cookie> {
                            // 在请求中添加保存的 Cookie
                            val cookies = cookieStore[url.host]
                            Log.d("CookieJar",cookies.toString())
                            return cookies ?: ArrayList()
                        }
                    }

                    val level = HttpLoggingInterceptor.Level.BODY
                    val loggingInterceptor = HttpLoggingInterceptor {
                        Log.d("HttpLoggingInterceptor", "OKHttp====Message:$it")
                    }
                    loggingInterceptor.level = level
                    client = OkHttpClient.Builder()
                        .connectTimeout(60, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .addInterceptor(loggingInterceptor)
                        .build()

                }
            }
        }
        return client
    }
}